import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:myapp/app/data/entities/article_item.dart';
import 'package:myapp/app/data/repository/info_repository.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class InfoListController extends GetxController {

  final _infoRepository = Get.find<IInfoRepository>();

  final _list = <ArticleItem>[].obs;

  RxList<ArticleItem> get list => _list;

  int get length => _list.length;

  String getUrl(int index) {
    if(index >= _list.length) return "";
    var item = _list[index];
    if(item is TextArticleItem) {
      return item.url;
    } else if(item is ImageArticleItem) {
      return item.url;
    } else if(item is MultipleImageArticleItem) {
      return item.url;
    }
    return "";
  }
  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
    _requestArticleList(true);
  }

  Future<void> _requestArticleList(bool refresh) async {
    try {
      final data = await _infoRepository.getArticleList();
      if(refresh) {
        _list.clear();
        _list.value = data;
        return;
      }
      _list.addAll(data);
    }catch(e) {
      Fluttertoast.showToast(msg: e.toString());
    }
  }

  void refresh() async {
    await _requestArticleList(true);
  }

  void loading() async {
    await _requestArticleList(false);
  }

  @override
  void onClose() {
  }
}
